<template>
    <div class="login">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px">
            <h3 class="title">登录系统</h3>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-button type="primary" @click="submit">登录</el-button>
        </el-form>
    </div>
</template>

<script>
import Mock from "mockjs"
import Cookie from "js-cookie";
import { getMenu } from "@/api";
import { mapMutations } from "vuex";
export default {
    data() {
        return {
            ruleForm: {
                username: '',
                password: '',
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                ],

            }
        }
    },
    methods: {
        ...mapMutations('tab', ['addMenu', 'setMenu']),
        // 登录
        submit() {
            // token信息
            // const token = Mock.Randon.guid()
            // token信息存入cookie用于不同页面间的通信
            // Cookie.set("token", token)
            // 跳转到首页
            // this.$router.push("/home")

            // 校验通过
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    getMenu(this.ruleForm).then(({ data }) => {
                        console.log(data);
                        if (data.code === 20000) {
                            // token信息存入cookie用于不同页面间的通信
                            Cookie.set("token", data.data.token)

                            // 获取菜单的数据，存入store中
                            this.setMenu(data.data.menu)
                            this.addMenu(this.$router)

                            // 跳转到首页
                            this.$router.push("/home")
                        } else {
                            this.$message.error(data.data.message)
                        }

                    })

                }

            })

        }
    },

}
</script>

<style lang="less" scoped>
.login {
    width: 20%;
    box-shadow: 0 0 10px rgba(0, 0, 0, .1);
    padding: 20px;
    text-align: center;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .title {
        text-align: center;
        line-height: 40px;
    }
}
</style>